#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
#include <linux/ioctl.h>

#define LEDOFF 0
#define LEDON 1
#define CLOSE_CMD 		(_IO(0XEF, 0x1)) 	/* 关闭定时器 */
#define OPEN_CMD 		(_IO(0XEF, 0x2)) 	/* 打开定时器 */
#define SETPERIOD_CMD 	(_IO(0XEF, 0x3)) 	/* 设置定时器周期命令 */


/* ./app /dev/* 1 5000 */

int main(int argc, char *argv[])
{
    int fd, retvalue;
    char *filename;
    unsigned int cmd;
    unsigned int period;
    unsigned char data[1];
    filename = argv[1];

    /* 打开 led 驱动 */
    fd = open(filename, O_RDWR);
    if (fd < 0)
    {
        printf("file %s open failed!\r\n", argv[1]);
        return -1;
    }

    data[0] = atoi(argv[2]); /* 要执行的操作：打开或关闭 */

    if(argc == 4)
    {
       
        switch (data[0])
        {
        case 0:
            cmd = CLOSE_CMD;
            break;
        case 1:
            cmd = OPEN_CMD;
            break;
        case 2:
            cmd = SETPERIOD_CMD;
            period = atoi(argv[3]);
            break;
        
        default:
            break;
        }
        ioctl(fd,cmd,period);
    }
    else
    {
        /* 向/dev/led 文件写入数据 */
        retvalue = write(fd, data, sizeof(data));
        if (retvalue < 0)
        {
            printf("LED Control Failed!\r\n");
            close(fd);
            return -1;
        }
    }
    


    retvalue = close(fd); /* 关闭文件 */
    if (retvalue < 0)
    {
        printf("file %s close failed!\r\n", argv[1]);
        return -1;
    }
    return 0;
}